package test1;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author: mornd
 * @dateTime: 2023/5/14 - 0:13
 */
public class App {
    public static void main(String[] args) {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));

        // 手动从 xml 中获取bean
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        reader.loadBeanDefinitions(new ClassPathResource("bean.xml"));
        System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));

        // 从配置类获取
        beanFactory.registerBeanDefinition("config",
                BeanDefinitionBuilder.genericBeanDefinition(Config.class).getBeanDefinition());
        // 解析 @bean 注解
        ConfigurationClassPostProcessor postProcessor = new ConfigurationClassPostProcessor();
        postProcessor.postProcessBeanDefinitionRegistry(beanFactory);
        System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));

        // 扫包方式
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanFactory);
        scanner.scan("test1");
        System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));
    }

    static class B1 {}
    static class B2 {}
    @Component
    static class B3 {}

    static class Config {

        @Bean
        public B2 b2() {
            return new B2();
        }
    }
}
